package com.ck.express.tcp

import android.util.Log
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder


import java.nio.charset.Charset

class TcpMessageEncoder : MessageToByteEncoder<String>() {
    override fun encode(ctx: ChannelHandlerContext, msg: String, out: ByteBuf) {
        val bodyBytes = msg.toByteArray(Charset.forName("GBK"))
        val lengthStr = bodyBytes.size.toString().padStart(8, '0')  // 变成8位数字字符串，如"00000213"
        val lengthBytes = lengthStr.toByteArray(Charset.forName("GBK"))     // 转成字节

        out.writeBytes(lengthBytes)  // 写8字节长度字符串（ASCII数字）
        out.writeBytes(bodyBytes)    // 写消息体.i("TcpMessageEncoder","开始写数据")
        // 打印写入的内容（从头到当前写指针）
        val writtenBytes = ByteArray(out.readableBytes())
        out.getBytes(out.readerIndex(), writtenBytes)


        println("Length bytes (hex): " + lengthBytes.joinToString(" ") { "%02x".format(it) })

        // 打印消息体部分（用GBK解码）
        val bodyBytesL = writtenBytes.copyOfRange(8, writtenBytes.size)
        println("Body as GBK string: " + String(bodyBytesL, Charset.forName("GBK")))
        Log.i("TcpMessageEncoder", "写数据结束")
    }
}
